<?php
namespace Utils;
use Aliyun\SignatureHelper;
class SmsCode {
	private $smsCode = 0;
	private static $conf = [
		'accessKeyId' => 'LTAIrG2knLbZQ7ab',
		'accessKeySecret' => 'yePzK8sC3raQLZbmT0QqrxbVq0w6Tl',
		'SignName' => '梦想插画社',
		'TemplateCode' => 'SMS_125117301',
	];
	
	public function __construct(){
		$this->generateCode();
	}
	
	public function generateCode(){
		$this->smsCode = mt_rand(100000, 999999);
	}
	
	public function getCode(){
		return $this->smsCode;
	}
	
	public function checkPhoneNum($phoneNum){
		if(preg_match('/^1[0-9]{10}$/', strval($phoneNum))){
			return true;
		} else {
			return false;
		}
	}
	
	public function sendSms($phoneNum){
		if($this->checkPhoneNum($phoneNum)){
			$params = [
				'PhoneNumbers' => $phoneNum,
				'SignName' => self::$conf['SignName'],
				'TemplateCode' => self::$conf['TemplateCode'],
				'TemplateParam' => [
					'code' => strval($this->smsCode),
				],
			];
			try {
				if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
					$params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
					$helper = new SignatureHelper();
					$content = $helper->request(
						self::$conf['accessKeyId'],
						self::$conf['accessKeySecret'],
						"dysmsapi.aliyuncs.com",
						array_merge($params, array(
							"RegionId" => "cn-hangzhou",
							"Action" => "SendSms",
							"Version" => "2017-05-25",
						))
						,true
					);
					if(isset($content->Code)){
						return $content->Code == 'OK'?true:$content->Code;
					} else {
						return 'ctx.UNDEFINED';
					}
				}
				
			} catch(Exception $e){
				return 'net.NOTCONNECT';
			}
		} else {
			return 'isv.MOBILE_NUMBER_ILLEGAL';
		}
	}
	
	public function getErrorMsg($code){
		$errorMsg = [
			'isp.RAM_PERMISSION_DENY' => 'RAM权限DENY',
			'isv.OUT_OF_SERVICE' => '业务停机',
			'isv.PRODUCT_UNSUBSCRIBE' => '产品未开通',
			'isv.ACCOUNT_NOT_EXISTS' => '账户不存在',
			'isv.ACCOUNT_ABNORMAL' => '账户异常',
			'isv.SMS_TEMPLATE_ILLEGAL' => '短信模板不合法',
			'isv.SMS_SIGNATURE_ILLEGAL' => '短信签名不合法',
			'isv.INVALID_PARAMETERS' => '参数异常',
			'isp.SYSTEM_ERROR' => '服务器内部错误',
			'isv.MOBILE_NUMBER_ILLEGAL' => '手机号不正确',
			'isv.MOBILE_COUNT_OVER_LIMIT' => '手机号码数量超过限制',
			'isv.TEMPLATE_MISSING_PARAMETERS' => '	模板缺少变量',
			'isv.BUSINESS_LIMIT_CONTROL' => '短信发送过于频繁，请稍后再试',
			'isv.INVALID_JSON_PARAM' => 'JSON参数不合法，只接受字符串值',
			'isv.BLACK_KEY_CONTROL_LIMIT' => '	黑名单管控',
			'isv.PARAM_LENGTH_LIMIT' => '参数超出长度限制',
			'isv.PARAM_NOT_SUPPORT_URL' => '不支持URL',
			'isv.AMOUNT_NOT_ENOUGH' => '账户余额不足',
			'isv.TEMPLATE_PARAMS_ILLEGAL' => '模板变量里包含非法关键字',
			'net.NOTCONNECT' => '无法访问接口',
			'default' => '暂无相关错误介绍',
			'ctx.UNDEFINED' => '接口返回数据不正确',
		];
		if(isset($errorMsg[$code])){
			return $errorMsg[$code];
		} else {
			return $code;
		}
	}
}